﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Classes;
using Microsoft.Phone.Applications.Common;
using System.Windows.Navigation;
using System.ComponentModel;
using Microsoft.Phone.Shell;
using System.Windows.Controls.Primitives;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Tasks;
using Motif;

namespace MemoBoss
{
    public enum CurrentView
    {
        MainMenu,
        OptionsMenu,
        AboutScreen,
        HelpScreen,
        GameScreen,
        CollectionScreen,
        DifficultySelect,
        ScoreBoards,
        _background
    }

    public partial class MainPage : Layers
    {
        // Constructor
        Options _optionsMenu;
        Options optionsMenu
        {
            get
            {
                if( _optionsMenu== null )
                {
                    _optionsMenu = new Options(BackToMainMenu, goToCollection, SetBackgroundPicture, StartAccelerometer);
                    _optionsMenu.LayoutRoot.Visibility = System.Windows.Visibility.Collapsed;

                    MenuPlaceholder.Children.Add(_optionsMenu);
                    
                    addLayer(optionsMenu, CurrentView.OptionsMenu);
                    
                }
                return _optionsMenu;
            }
        }

        About _aboutScreen;
        About aboutScreen
        {
            get
            {
                if (_aboutScreen == null)
                {
                    _aboutScreen = new About(BackToMainMenu, SetBackgroundPicture);
                    _aboutScreen.LayoutRoot.Visibility = System.Windows.Visibility.Collapsed;

                    MenuPlaceholder.Children.Add(_aboutScreen);

                    addLayer(aboutScreen, CurrentView.AboutScreen);
                  
                }
                return _aboutScreen;
            }
        }
        Help _helpScreen;
        Help helpScreen
        {
            get
            {
                if (_helpScreen == null)
                {
                    _helpScreen = new Help(BackToMainMenu, SetBackgroundPicture);
                    _helpScreen.LayoutRoot.Visibility = System.Windows.Visibility.Collapsed;

                    MenuPlaceholder.Children.Add(_helpScreen);
                  
                    addLayer(helpScreen, CurrentView.HelpScreen);
                   
                }
                return _helpScreen;
            }
        }
        GameScreen _gameScreen;
        GameScreen gameScreen
        {
            get
            {
                if (_gameScreen == null)
                {
                    _gameScreen = new GameScreen(BackToMainMenu, SetBackgroundPicture);
                    _gameScreen.LayoutRoot.Visibility = System.Windows.Visibility.Collapsed;

                    ContentPanel.Children.Add(_gameScreen);
                 
                    addLayer(gameScreen, CurrentView.GameScreen);
                }
                return _gameScreen;
            }
        }
        CollectionScreen _collectionScreen;
        CollectionScreen collectionScreen
        {
            get
            {
                if (_collectionScreen == null)
                {
                    _collectionScreen = new CollectionScreen(BackToMainMenu, SetBackgroundPicture);
                    _collectionScreen.LayoutRoot.Visibility = System.Windows.Visibility.Collapsed;

                    ContentPanel.Children.Add(_collectionScreen);
                    _collectionScreen.galleryPanorama.ApplyTemplate();

                   
                    addLayer(collectionScreen, CurrentView.CollectionScreen);
                   
                }
                return _collectionScreen;
            }
        }
        DifficultySelect _difficultySelect;
        DifficultySelect difficultySelect
        {
            get
            {
                if (_difficultySelect == null)
                {
                    _difficultySelect = new DifficultySelect(BackToMainMenu, SetBackgroundPicture, PlayGame);
                    _difficultySelect.LayoutRoot.Visibility = System.Windows.Visibility.Collapsed;

                    MenuPlaceholder.Children.Add(_difficultySelect);

                    addLayer(difficultySelect, CurrentView.DifficultySelect);
                   

                }
                return _difficultySelect;
            }
        }
        ScoreboardScreen _scoreboardScreen;
        ScoreboardScreen scoreboardScreen
        {
            get
            {
                if (_scoreboardScreen == null)
                {
                    _scoreboardScreen = new ScoreboardScreen(BackToMainMenu, SetBackgroundPicture);
                    _scoreboardScreen.LayoutRoot.Visibility = System.Windows.Visibility.Collapsed;

                    MenuPlaceholder.Children.Add(_scoreboardScreen);

                    addLayer(scoreboardScreen, CurrentView.ScoreBoards);

                }
                return _scoreboardScreen;
            }
        }
        public MainPage()
        {
            InitializeComponent();

            App.BGMusicPlayerInstance = this.BGMusic;



            AdDuplex.IsEnabled = true;
            AdDuplex.Visibility = System.Windows.Visibility.Visible;
              //if (App.IsTrial)
              //{
              //    AdDuplex.IsEnabled = true;
              //    AdDuplex.Visibility = System.Windows.Visibility.Visible;
              //}
              //else
              //{
              //    AdDuplex.IsEnabled = false;
              //    AdDuplex.Visibility = System.Windows.Visibility.Collapsed;
              //}
        
        }
        private void showMainMenu()
        {
            ShowMainMenu.Begin();
        }
        private void showMainPage()
        {
            ShowMainPage.Begin();
        }
        //// Simple button Click event handler to take us to the second page
        //private void Button_Click(object sender, RoutedEventArgs e)
        //{
        //    NavigationService.Navigate(new Uri("/GamePage.xaml", UriKind.Relative));
        //}

        private void btnHelp_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            SoundFX.PlaySoundEffect(SFX.ButtonClick);
            HideMainMenu.Begin();
            helpScreen.Show.Begin();
            subMenuHide = helpScreen.ExitScreen;
            App.currentView = CurrentView.HelpScreen;

        }

        private void btnAbout_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            SoundFX.PlaySoundEffect(SFX.ButtonClick);
            HideMainMenu.Begin();
            aboutScreen.Show.Begin();
            subMenuHide = aboutScreen.ExitScreen;
            App.currentView = CurrentView.AboutScreen;

        }

        private void btnRate_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            SoundFX.PlaySoundEffect(SFX.ButtonClick);
            MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
            marketplaceReviewTask.Show();

        }

        private void btnBuy_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            SoundFX.PlaySoundEffect(SFX.ButtonClick);
            MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();
            marketplaceDetailTask.Show();
        }

        private void btnFacebook_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            SoundFX.PlaySoundEffect(SFX.ButtonClick);
            WebBrowserTask webbrowser = new WebBrowserTask();
            webbrowser.Uri = new Uri("http://www.facebook.com/studiomotif");
            webbrowser.Show();
        }

        private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
        {
            //Dispatcher.BeginInvoke(() => //kitaip neišeina nustatyti lango dydžio
            // {
        
            addLayer(MainPageContent, CurrentView.MainMenu);
          
            addManualLayerControl(bgImage1);
            addManualLayerControl(bgImage2);
            addManualLayerControl(logoImage);
            StartAccelerometer();
            // });
        }

        private void btnPlay_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            checkImages();
            if (imagesCount < 20)
            {
                MessageBox.Show("You need at least 20 images to play the game. Please go to the options menu to select images from your media library.");
                return;
            }
            SoundFX.PlaySoundEffect(SFX.ButtonClick);
            // gameScreen.ClearGameScreen();
            HideMainMenu.Begin();
            difficultySelect.Show.Begin();
            subMenuHide = difficultySelect.ExitScreen;
            App.currentView = CurrentView.DifficultySelect;
            //Dispatcher.BeginInvoke(() =>
            //{
            //    this.NavigationService.Navigate(new Uri("/GamePage.xaml", UriKind.Relative));
            //});
        }

        private void PlayGame(DifficultyLevel difficulty)
        {
            gameScreen.currentDifficultyLevel = difficulty;
            gameScreen.ClearGameScreen();
            HideMainPage.Begin();
            gameScreen.Show.Begin();

            subMenuHide = gameScreen.ExitScreen;
            App.currentView = CurrentView.GameScreen;
            //Dispatcher.BeginInvoke(() =>
            //{
            //    this.NavigationService.Navigate(new Uri("/GamePage.xaml", UriKind.Relative));
            //});
        }

        private void Rectangle_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {

        }


        private void btnOptionsGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Push.Stop();
            Push.Children.ToList().ForEach(a => Storyboard.SetTarget(a, (DependencyObject)sender));
            Push.Begin();
        }

        private void btnOptionsGrid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {

        }

        private void btnOptionsGrid_MouseLeave(object sender, MouseEventArgs e)
        {
            Release.Stop();
            Release.Children.ToList().ForEach(a => Storyboard.SetTarget(a, (DependencyObject)sender));
            Release.Begin();
        }



        Action subMenuHide;
        private void btnOptions_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            SoundFX.PlaySoundEffect(SFX.ButtonClick);
            HideMainMenu.Begin();
            optionsMenu.Show.Begin();
            subMenuHide = optionsMenu.ExitScreen;
            App.currentView = CurrentView.OptionsMenu;
        }

        private void BackToMainMenu()
        {
            SoundFX.PlaySoundEffect(SFX.BackButtonClick);
            checkImages();
            if (App.currentView == CurrentView.GameScreen)
            {
                ShowMainPage.Begin();
                App.currentView = CurrentView.MainMenu;
                return;
            }
            if (App.currentView == CurrentView.OptionsMenu)
            {
                ShowMainMenu.Begin();
                App.currentView = CurrentView.MainMenu;
                return;
            }
            subMenuHide();

            if (App.currentView == CurrentView.CollectionScreen)
            {
                optionsMenu.Show.Begin();
                ShowMainPage.Begin();
                App.currentView = CurrentView.OptionsMenu;
                subMenuHide = optionsMenu.ExitScreen;
                return;
            }
            else
            {

                ShowMainMenu.Begin();
            }
            App.currentView = CurrentView.MainMenu;
        }

        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            if (App.currentView == CurrentView.GameScreen)
            {
                subMenuHide();
                e.Cancel = true;
                return;
            }
            if (App.currentView == CurrentView.OptionsMenu)
            {
                subMenuHide();
                e.Cancel = true;
                return;
            }
            if (App.currentView != CurrentView.MainMenu)
            {
                this.BackToMainMenu();
                e.Cancel = true;
            }

            if (popup != null && popup.IsOpen)
            {
                popupDiag.ReturnDefault();
                e.Cancel = true;
            }



            if (App.currentView == CurrentView.CollectionScreen)
            {
                this.BackToMainMenu();
                e.Cancel = true;
            }



            base.OnBackKeyPress(e);


        }

        private void goToCollection()
        {
            if (App.currentView == CurrentView.MainMenu)
            {
                HideMainMenu.Begin();
            }
            HideMainPage.Begin();
            collectionScreen.Show.Begin();
            subMenuHide = collectionScreen.ExitScreen;
            App.currentView = CurrentView.CollectionScreen;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            SetBackgroundPicture();
            SoundHelper.instance.PlayMusic(App.BGMusicPath, App.SettingsInstance.MusicOnOffSetting, false);
            //if (App.IsTrial)
            //{
            //    btnBuy.Visibility = System.Windows.Visibility.Visible;
            //    txtBuy.Visibility = System.Windows.Visibility.Visible;
            //}
            //else
            //{
                btnBuy.Visibility = System.Windows.Visibility.Collapsed;
                txtBuy.Visibility = System.Windows.Visibility.Collapsed;
            //}
            if (App.currentView == CurrentView.GameScreen)
            {
                gameScreen.GameSceenOnNavigatedTo();
            }
            Dispatcher.BeginInvoke(() => //kitaip neišeina nustatyti lango dydžio
            {
                if (!App.IsActivated)
                {
                    if (App.AppLaunchCount == 0)
                    {
                        string text = "Welcome to Memo Boss! This game uses your phones gallery images. Please choose whether you want to use all the images in your collection or select specific images. You need at least 20 to play the game.";
                        showPopup(ImageSettingsCallback, text, "Use all", "Select", true);
                    }
                    if (App.AppLaunchCount == 5)
                    {
                        string text = "So you're back! Did you like Memo Boss? Would you like to rate it?";
                        showPopup(RateCallback, text, "Rate it", "No thanks", false);
                    }
                }
                checkImages();
            });
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            if (App.currentView == CurrentView.GameScreen)
            {
                gameScreen.Pause();
            }
        }

        private int imagesCount;
        private void checkImages()
        {

            if (App.SettingsInstance.UseAllImagesSetting)
            {
                imagesCount = ImageCollection.getTotalImagesCountInMediaLibrary();
            }
            else
            {
                var ml = new Microsoft.Xna.Framework.Media.MediaLibrary();
                using (var pictures = ml.Pictures)
                {
                    //App.collection.PicturesCollection.Where(p=> pictures.First(p => p.GetHashCode() == pict.Key) )
                    int ActualCnt = pictures.Where(p => App.collection.PicturesCollection.ContainsKey(p.GetHashCode())).Count();
                    imagesCount = App.collection.PicturesCollection.Count;
                    if (ActualCnt < imagesCount)
                    {
                        var existingPics = pictures.Where(p => App.collection.PicturesCollection.ContainsKey(p.GetHashCode()));
                        var dict = existingPics.ToDictionary(p => p.GetHashCode(), p => true);
                        var missingPics = App.collection.PicturesCollection.Where(p => !dict.ContainsKey(p.Key)).ToDictionary(x => x.Key, x => x.Value);
                        if (missingPics.Count() > 0)
                        {
                            foreach (KeyValuePair<int, int> pic in missingPics)
                            {
                                App.collection.PicturesCollection.Remove(pic.Key);
                            }
                        }
                        imagesCount = App.collection.PicturesCollection.Count;
                        App.collection.Save();
                        //App.collection.PicturesCollection.Where(p=> !existingPics.(p.key == ))
                    }
                }

            }
            if (imagesCount < 20) { imgStop.Visibility = Visibility.Visible; } else imgStop.Visibility = Visibility.Collapsed;
            //if (cnt < 20) 
            //{
            //    MessageBox.Show("You need at least 20 images to")
            //}
        }

        Popup popup = null;
        PopupDialog popupDiag;
        private void showPopup(Action<bool> callback, string text, string btn1Text, string btn2Text, bool defaultResult)
        {
            SuspendLayout();
            if (popup == null)
            {
                popup = new Popup();


            }
            popupDiag = new PopupDialog(callback, text, btn1Text, btn2Text, defaultResult);


            popup.Child = popupDiag;




            popup.IsOpen = true;
            popupDiag.Opacity = 0;
            popupDiag.UpdateLayout();
            popup.VerticalOffset = 50;//(App.Current.RootVisual as FrameworkElement).ActualHeight / 2 - popupDiag.ActualHeight / 2;

            popup.HorizontalOffset = (App.Current.RootVisual as FrameworkElement).ActualWidth / 2 - popupDiag.ActualWidth / 2;

            popupDiag.Opacity = 1;
            //CardsPanel.Visibility = System.Windows.Visibility.Collapsed;


        }

        void RateCallback(bool result)
        {

            if (result)
            {
                if (popup != null)
                    popup.IsOpen = false;
                ReleaseLayout();
                MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
                marketplaceReviewTask.Show();
            }
            else
            {
                if (popup != null)
                    popup.IsOpen = false;
                ReleaseLayout();
            }
        }

        void ImageSettingsCallback(bool result)
        {

            if (result)
            {
                App.SettingsInstance.UseAllImagesSetting = true;

                if (popup != null)
                    popup.IsOpen = false;
                ReleaseLayout();

            }
            else
            {
                App.SettingsInstance.UseAllImagesSetting = false;

                if (popup != null)
                    popup.IsOpen = false;
                ReleaseLayout();

                goToCollection();


            }

        }




        void SuspendLayout()
        {
            LayoutRoot.IsHitTestVisible = false;

        }
        void ReleaseLayout()
        {
            LayoutRoot.IsHitTestVisible = true;

        }

        private void ShowMainPage_Completed(object sender, EventArgs e)
        {
            if (App.currentView == CurrentView.MainMenu)
            {
                SetBackgroundPicture();
            }
        }

        private void ShowMainMenu_Completed(object sender, EventArgs e)
        {
            if (App.currentView == CurrentView.MainMenu)
            {
                SetBackgroundPicture();
            }
        }

        private void btnScoreboard_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            scoreboardScreen.startLoad();
            SoundFX.PlaySoundEffect(SFX.ButtonClick);
            HideMainMenu.Begin();
            scoreboardScreen.Show.Begin();
            subMenuHide = scoreboardScreen.ExitScreen;
            App.currentView = CurrentView.ScoreBoards;
        }


    }
}